package com.zdlyh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zdlyh.domain.entity.LoginUser;
import com.zdlyh.domain.entity.User;
import com.zdlyh.mapper.MenuMapper;
import com.zdlyh.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        // 根据用户名查询用户信息
        queryWrapper.eq(User::getEmail,email);
        User user = userMapper.selectOne(queryWrapper);
        // 先判断传进来的用户名是否存在
        if (Objects.isNull(user)){
            throw new RuntimeException("这个邮箱不存在");
        }
        // 返回用户信息
        // 查询权限信息封装  (只有后台需要，前台只需要token)
        if (user.getType().equals("1")){
            List<String> perms = menuMapper.getPermsByUserId(user.getId());
            return new LoginUser(user,perms);
        }
        return new LoginUser(user,null);
    }
}